#include <stdio.h>
#include "my_usart.h"

static const int RX_BUF_SIZE = 1024;
static void my_usart_tx_task(void *arg);
static void my_usart_rx_task(void *arg);

void my_usart_init(void)
{
    const uart_config_t uart_config = {
        .baud_rate = my_uart_baud,//波特率
        .data_bits = my_uart_data_size,//数据大小
        .parity = my_uart_set_parity,//奇偶校验位
        .stop_bits = UART_STOP_BITS_1,//停止位
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,//流量控制模式
        .source_clk = UART_SCLK_APB,//串口时钟源选择
    };
    //安装串口驱动程序
    uart_driver_install(UART_NUM_1, RX_BUF_SIZE*2, 0, 0, NULL, 0);
    uart_param_config(UART_NUM_1, &uart_config);//配置UART
    uart_set_pin(UART_NUM_1, my_Tx_PIN, my_Rx_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);//设置引脚
}
int my_usart_sendData(const char* logName, const char* data)
{
    const int len = strlen(data);//计算数据长度
    const int txBytes = uart_write_bytes(UART_NUM_1, data, len);//返回为串口写入的字节数
    // ESP_LOGI("Write %d bytes", txBytes);
    ESP_LOGI(logName, "Write %d bytes", txBytes);
    printf("%s\n",data);
    return txBytes;
}
static void my_usart_tx_task(void *arg)
{
    static const char *TX_TASK_TAG = "TX_TASK";
    esp_log_level_set(TX_TASK_TAG, ESP_LOG_INFO);
    while (1)
    {
        my_usart_sendData(TX_TASK_TAG,"Hello world111");
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
}
static void my_usart_rx_task(void *arg)
{
    static const char *RX_TASK_TAG = "RX_TASK";
    esp_log_level_set(RX_TASK_TAG, ESP_LOG_INFO);
    uint8_t* data = (uint8_t*) malloc(RX_BUF_SIZE+1);//分配一个内存块
    while (1) {
        const int rxBytes = uart_read_bytes(UART_NUM_1, data, RX_BUF_SIZE, 1000 / portTICK_RATE_MS);//读取内存块的数据，没数据返回-1，读到就返回数据的长度
        if (rxBytes > 0) {
            data[rxBytes] = 0;
            ESP_LOGI(RX_TASK_TAG, "Read %d bytes: '%s'", rxBytes, data);
            ESP_LOG_BUFFER_HEXDUMP(RX_TASK_TAG, data, rxBytes, ESP_LOG_INFO);
        }
    }
    free(data);//释放内存块
}
void run_usart_task(void)
{
    my_usart_init();
    xTaskCreate(my_usart_rx_task, "uart_rx_task", 1024*2, NULL, configMAX_PRIORITIES, NULL);
    xTaskCreate(my_usart_tx_task, "uart_tx_task", 1024*2, NULL, configMAX_PRIORITIES-1, NULL);
}

